package org.gcu.filestorage.uitls;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;
import java.util.Map;

@Slf4j
public class TokenUtil {
    private static final String TOKEN_SECRET = "gcu_file_storage";
    private static final String ACCOUNT = "account";

    /**
     * 根据传入的签名, 将账号信息加入到有效载荷
     *
     * @param account 账号
     * @return 返回携带账号的Token
     */
    public static String genToken(String account) {
        String token = "";
        try {
            token = JWT.create()
                    .withClaim(ACCOUNT, account)
                    .withExpiresAt(new Date(System.currentTimeMillis() + 24 * 60 * 60 * 1000))
                    .sign(Algorithm.HMAC256(TOKEN_SECRET));
        } catch (IllegalArgumentException | JWTCreationException e) {
            log.error("genToken()", e);
        }
        return token;
    }

    public static String parseAccount(String token) {
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(TOKEN_SECRET)).build();
            DecodedJWT decodedJWT = verifier.verify(token);
            Map<String, Claim> claims = decodedJWT.getClaims();
            return claims.get(ACCOUNT).asString();
        } catch (JWTVerificationException e) {
            log.error("parseAccount()", e);
            return "";
        }
    }
}
